<template>
  <div class="app-container news-container">
    <el-form size="mini" :inline="true" :model="searchForm" @keyup.enter.native="getDataList()">
      <el-form-item label="查询：">
        <el-input clearable placeholder="输入主题名称" style="width: 300px" v-model="searchForm.title"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" @click="getDataList()" icon="el-icon-search" type="primary">查询</el-button>
        <el-button size="mini" @click="refDataList()" icon="el-icon-refresh" type="primary">重置</el-button>
        <el-button size="mini" @click="addOrUpdateHandle()" type="primary" v-if="Jurisdictionlist.indexOf('Add') > -1">添加 </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" size="mini" :height="tableHeight" border ref="table" style="width: 100%" v-loading="dataListLoading">
      <el-table-column align="center" header-align="center" label="序号" prop="typeName" width="80">
        <template slot-scope="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="主题" prop="title"></el-table-column>
      <el-table-column align="center" header-align="center" label="图片" prop="url">
        <template slot-scope="scope">
          <img :src="scope.row.url" width="40" />
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="启用状态" prop="status">
        <template slot-scope="scope">
          {{ scope.row.status === 0 ? '禁用 ' : '启用' }}
        </template>
      </el-table-column>
      <el-table-column align="center" header-align="center" label="排序值" prop="order"></el-table-column>
      <el-table-column align="center" header-align="center" label="创建人" prop="created_user"></el-table-column>
      <el-table-column align="center" header-align="center" label="创建时间" prop="created_time"></el-table-column>
      <el-table-column align="center" fixed="right" header-align="center" label="操作" width="320">
        <template slot-scope="scope">
          <el-button size="mini" @click="addOrUpdateHandle(scope.row)" plain type="primary" v-if="Jurisdictionlist.indexOf('Edit') > -1">编辑 </el-button>
          <el-button size="mini" @click="handleDel(scope.row)" plain type="danger" v-if="Jurisdictionlist.indexOf('Delete') > -1">删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination small :current-page="pageIndex" :page-size="pageSize" :page-sizes="[10, 20, 50, 100]" :total="totalPage" @current-change="currentChangeHandle" @size-change="sizeChangeHandle" layout="total, sizes, prev, pager, next, jumper" style="margin-top: 10px"></el-pagination>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update @refreshList="getDataList" ref="addOrUpdate"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './add-or-update'
import { mapGetters } from 'vuex'
import { DeleteBannerApi, ListBannerApi } from '../../../api/banner'

var app

export default {
  name: 'SerClassManage',
  computed: {
    ...mapGetters(['name']),
  },
  beforeCreate() {
    app = this
  },
  filters: {},
  data() {
    return {
      uploadVisible: false,
      allMainBodyArr: [],
      allAreaArr: [],
      allQyArr: [],
      //////////////////////////
      Jurisdictionlist: [], // 权限列表
      newcontent: '', // 公告内容
      searchForm: {
        title: '',
      },
      dialogTableVisible: false,
      dataList: [],
      tableHeight: 50,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      areaIdArr: [],
      mainBodyArr: [],
      addOrUpdateVisible: false,
      sts_lis: [
        { value: '1', label: '正常' },
        { value: '0', label: '冻结' },
      ],
      batchArr: [],
    }
  },
  components: { AddOrUpdate },
  mounted() {
    // this.getAllMainBodiesArr();
    // this.getAllAreaArr();
    // this.getAllQiyeArr();
    this.getDataList()
    // this.getMainBodiesFun();
    // this.getAreaArrFun();
    this.Jurisdictionlist = JSON.parse(localStorage.getItem('jurisdiction'))[this.$route.path]
    this.$nextTick(function () {
      this.tableHeight = window.innerHeight - 165 - 65
      // 监听窗口大小变化
      let self = this
      window.onresize = function () {
        self.tableHeight = window.innerHeight - 165 - 65
      }
    })
  },
  methods: {
    UploadFile(param) {
      let _this = this
      const formData = new FormData()
      formData.append('file', param.file)
      BatchImportUserApi(formData)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('导入成功')
            this.getDataList()
          }
        })
        .catch((response) => {})
    },
    ////////////////////////
    getAllMainBodiesArr() {
      mainBodiesAllApi().then((res) => {
        if (res.code == 200) {
          this.allMainBodyArr = res.result
        }
      })
    },
    getAllAreaArr() {
      areaAllApi().then((res) => {
        if (res.code == 200) {
          this.allAreaArr = res.result
        }
      })
    },
    getAllQiyeArr() {
      CustomerAllApi().then((res) => {
        if (res.code == 200) {
          this.allQyArr = res.result
        }
      })
    },
    batchImportHandle() {
      this.$message.error('暂未启用此功能')
    },
    downLoadMuban() {
      // this.$message.error('暂未添加模板');
      // this.download(baseApi + 'media/muban/用户导入模板.xlsx','用户导入模板.xlsx');
      window.location = '/用户导入模板.xlsx'
    },
    download(url, filename) {
      return fetch(url).then((res) =>
        res.blob().then((blob) => {
          let a = document.createElement('a')
          let url = window.URL.createObjectURL(blob)
          a.href = url
          a.download = filename
          a.click()
          window.URL.revokeObjectURL(url)
        })
      )
    },

    // TODO 导出
    exportHandle() {
      if (this.batchArr.length > 0) {
        this.exportFunction(this.batchArr)
      } else {
        const info = Object.assign({ all: true }, { search: this.searchForm })
        ListClientUserApi(info).then((res) => {
          this.exportFunction(res.result.items)
        })
      }
    },
    exportFunction(lis) {
      const headerProperty = ['mainBodyId_id', 'areaId_id', 'qyId_id', 'name', 'position', 'phone', 'desc', 'created_time']
      // 主体，区域，所属企业，人员名称，职位，联系电话，备注，添加时间
      const headerLabel = ['主体', '区域', '所属企业', '人员名称', '职位', '联系电话', '备注', '添加时间']
      const name = '用户明细'
      const list = lis.map((item) => {
        if (item.mainBodyId_id) {
          var mainBodyId_name
          app.allMainBodyArr.forEach(function (element) {
            if (element.id === item.mainBodyId_id) {
              mainBodyId_name = element.name
            }
          })
          item.mainBodyId_id = mainBodyId_name
        } else {
          item.mainBodyId_id = '-'
        }
        if (item.areaId_id) {
          var areaId_name
          app.allAreaArr.forEach(function (element) {
            if (element.id === item.areaId_id) {
              areaId_name = element.name
              return false
            }
          })
          item.areaId_id = areaId_name
        } else {
          item.areaId_id = '-'
        }
        if (item.qyId_id) {
          var qyId_name
          app.allQyArr.forEach(function (element) {
            if (element.id === item.qyId_id) {
              qyId_name = element.name
              return false
            }
          })
          item.qyId_id = qyId_name
        } else {
          item.qyId_id = '-'
        }
        return item
      })
      this.handleDownload(headerProperty, list, headerLabel, name)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    },
    handleDownload(headerProperty, list, headerLabel, name) {
      import('@/vendor/Export2Excel').then((excel) => {
        const data = this.formatJson(headerProperty, list)
        excel.export_json_to_excel({
          header: headerLabel,
          data,
          filename: name,
          autoWidth: this.autoWidth,
          bookType: 'xlsx',
        })
      })
    },
    ////////////////////////////////////////
    batchDelete() {
      const batch_ids = []
      this.select_arr.forEach(function (ele) {
        batch_ids.push(ele.id)
      })
      DeleteClientUserApi({ ids: batch_ids }).then((res) => {
        this.getDataList()
      })
    },
    changeMainBodyId() {
      this.getAreaArrFun()
    },
    getAreaArrFun() {
      areaArrApi({ main_body_id: this.searchForm.mainBodyId }).then((res) => {
        this.areaIdArr = res.result
      })
    },
    getMainBodiesFun() {
      mainBodiesApi().then((res) => {
        this.mainBodyArr = res.result
      })
    },
    //重置
    refDataList() {
      this.searchForm = {
        title: '',
      }
      this.getDataList()
    },
    showRowContent(row) {
      this.$nextTick(() => {
        this.dialogTableVisible = true
        this.newcontent = row.content
        // this.$refs.quillEditIndex.open(row)
      })
    },
    handleDel(row) {
      this.$confirm('确认删除吗?', '提示', {
        type: 'warning',
      })
        .then(() => {
          let para = {
            ids: [row.id],
          }
          DeleteBannerApi(para).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功')
              this.getDataList()
            }
          })
        })
        .catch(() => {})
    },
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.searchForm.date = this.searchForm.date || []
      const info = Object.assign({ pageNumber: this.pageIndex, pageSize: this.pageSize }, this.searchForm)
      ListBannerApi(info)
        .then((res) => {
          this.dataList = res.result.items
          this.totalPage = res.result.total
          this.dataListLoading = false
        })
        .catch((e) => {
          this.dataList = []
          this.totalPage = 0
          this.dataListLoading = false
        })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.batchArr = val
    },
    // 新增 / 修改
    addOrUpdateHandle(row) {
      this.$refs.addOrUpdate.open(row, this.roleOptions)
    },
  },
}
</script>

<style lang="scss" scoped>
.fl {
  float: left;
}

.fr {
  float: right;
}

.clearfix::after {
  content: '';
  display: block;
  clear: both;
}

.thiscontainer {
}
</style>
